package cz.jm.web.manhunter.server;

import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import cz.jm.web.manhunter.server.authentication.Account;
import cz.jm.web.manhunter.shared.SharedConstants;

public class MailSender {
	
	public static void sendMail(String to, String subject, String text) {
		String host = "smtp.gmail.com";
		String from = "manhunter.automatic@gmail.com";
		String pass = "8769jata";
		
		Properties props = System.getProperties();
	    props.put("mail.smtp.starttls.enable", "true"); // added this line
	    props.put("mail.smtp.host", host);
	    props.put("mail.smtp.user", from);
	    props.put("mail.smtp.password", pass);
	    props.put("mail.smtp.port", "587");
	    props.put("mail.smtp.auth", "true");
		

		Session session = Session.getDefaultInstance(props, null);
		MimeMessage message = new MimeMessage(session);
		try {
			message.setFrom(new InternetAddress(from));
			message.addRecipient(Message.RecipientType.TO,  new InternetAddress(to));
			message.setSubject(subject);
			message.setText(text);
			
		    Transport transport = session.getTransport("smtp");
		    transport.connect(host, from, pass);
		    transport.sendMessage(message, message.getAllRecipients());
		    transport.close();
		} catch (AddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MessagingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	

	

	public static void sendRegistrationMail(Account account) {
		// TODO vytknut niekde adresu hostu asi do nejakeho konfiguraku.
		String address = "http://127.0.0.1:8888/ManHunter.html?gwt.codesvr=127.0.0.1:9997";
		address += "&" + SharedConstants.USER_ID + "=" + account.getId();
		address += "&"+ SharedConstants.REGISTRATION_KEY +"=" +  account.getUsername().hashCode();
		address += account.getRegistrationDate().hashCode();
		address += account.getMail().hashCode();
						
		sendMail(account.getMail(), "confirm man-hunter registration", 
				"Please confirm your registration on man-hunter at " + address);
	}

}
